const { writeFileSync } = require('fs')
const net = require('net')
console.log(process.env.NODE_DEBUG)
const server = net.createServer({
	keepAlive: true,
})

const config = require('./config')(server)
const Proxy = require('./proxy')(server)

server.listen(config.port, config.host)
.on('listening', () => {
	console.log(`simple-proxy server listening on ${config.port}`)
})
.on('close', () => {
	console.log('simple-proxy server closed')
})
.on('error', e => {
	console.error('simple-proxy server throw error', e)
})
.on('connection', socket => {

	const proxy = Proxy(socket)

	let i = 1
	socket.on('data', buf => {
		writeFileSync(`./buf${i++}`, [...buf].toString())
		proxy.handle(buf)
	})
	.on('end', () => {
		console.log(`socket ${proxy._session.id} end`)
	})
	.on('close', hadError => {
		console.log(`socket ${proxy._session.id} closed with error ${hadError}`)
	})
	.on('error', err => {
		console.log(err.stack)
		console.error(`socket ${proxy._session.id} throw error`, err)
	})
	.on('timeout', () => {
		console.log(`socket ${proxy._session.id} timeout`)
	})
})
